<%@ page pageEncoding="UTF-8"%>
<%!
	// 微信模板信息生成
	public Map<String, Object> makeContent(Map<String, String>... maps) {
		Map<String, Object> model = new HashMap<String, Object>(); // 最后的模板
		Map<String, String> colors = new HashMap<String, String>(); // 放入颜色
		if (maps == null || maps.length < 1 || maps[0] == null)
			return model;
		if (maps.length == 2) {
			colors = maps[1];
		}
		Set<Entry<String, String>> keySet = maps[0].entrySet();
		String color = "#173177";
		for (Entry<String, String> entry : keySet) {
			String key = entry.getKey();
			String value = entry.getValue();
			Map<String, String> map = new HashMap<String, String>();
			map.put("value", value);
			map.put("color", colors.get(key) == null ? color : colors.get(key));
			model.put(key, map);
		}
		return model;
	}

	public Map getHospital(int hospital){
		// 医院信息
		List list = QBuilder.db("basedb").queryHql("from hospital where hospital =" + hospital + "");
		String json = "{}";
		if (list.size () > 0) {
			Map map = (Map)list.get(0);
			json = map.get("json") + "";
		}
		Map result = GsonUtil.fromJson(json, new TypeToken<HashMap>(){});
		return result;
	}

	// 获取公众号token
	public String token(int hospital){
		String url ="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + appsecret + "";//获得该公众号的token
		String tokenJson = HttpUtil.get(url);//拿到这个公众号对应的token
	    HashMap tokeMap = GsonUtil.fromJson(tokenJson, new TypeToken<HashMap>(){});
	    String token =  Tools.getDesc(tokeMap.get("access_token"), "");
		return token;
	}

	// 推送微信
	public Message template(String message, int hospital){
		Message msg = new Message();
		try{
			String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token(hospital);
			String html = HttpUtil.soap(url, message, "UTF-8");
			HashMap result = GsonUtil.fromJson(html, new TypeToken<HashMap>(){});
			return new Message(((Double)result.get("errcode")).intValue(), (String)result.get("errmsg"));
		} catch(Exception e) {
			e.printStackTrace();
			setErrcode(msg, SEND_ERROR);
		}
		return msg;
	}

	public String streamToString(InputStream inputStream, String encode) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int len = 0;
		String result = "";
		if (inputStream != null) {
			try {
				while ((len = inputStream.read(data)) != -1) {
					outputStream.write(data, 0, len);
				}
				result = new String(outputStream.toByteArray(), encode);
				outputStream.close();
				inputStream.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	public String SHA1(String decript) {
		try {
			java.security.MessageDigest digest = java.security.MessageDigest
					.getInstance("SHA-1");
			digest.update(decript.getBytes());
			byte messageDigest[] = digest.digest();
			// Create Hex String
			StringBuffer hexString = new StringBuffer();
			// 字节数组转换为 十六进制 数
			for (int i = 0; i < messageDigest.length; i++) {
				String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
				if (shaHex.length() < 2) {
					hexString.append(0);
				}
				hexString.append(shaHex);
			}
			return hexString.toString();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	// 服务器配置校验
	public String sign(HttpServletRequest request) {
		 String signature = request.getParameter("signature");
		 String timestamp = request.getParameter("timestamp");
		 String nonce = request.getParameter("nonce");
	     String token = "weixin";
		 List<String> list = new ArrayList<String>();
		 list.add(nonce);
		 list.add(timestamp);
		 list.add(token);
		 String[] arrayToSort = list.toArray(new String[list.size()]);
         Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
		 StringBuffer sb = new StringBuffer();
		 for (int i = 0; i < arrayToSort.length; i++) {
			sb.append(arrayToSort[i]);
		 }
	     String tmpStr = sb.toString();
		 tmpStr = SHA1(tmpStr);
		 if (tmpStr.equals(signature)) {
			return request.getParameter("echostr");
		 }
		 return "";
	}

	// 获取最终的xml信息
	public Map<String, String> parseXML(String xml) throws Exception {
		org.dom4j.Document document = org.dom4j.DocumentHelper.parseText(xml);
		org.dom4j.Element root = document.getRootElement();
		List<org.dom4j.Element> list = root.elements();
		Map<String, String> map = new HashMap<String, String>();
		for (int i = 0; i < list.size(); i++) {
			org.dom4j.Element element = list.get(i);
			map.put(element.getName(), element.getTextTrim());
		}
		return map;
	}

	// 递归创建相应消息
	public void createXML(Map<String, Object> map, org.dom4j.Element root) throws Exception {
		Set<Entry<String, Object>> set = map.entrySet();
		for (Entry<String, Object> entry : set) {
			String node = entry.getKey();
			Object value = entry.getValue();
			org.dom4j.Element element = root.addElement(node);
			if (value instanceof Map) {
				createXML((Map)value, element);
			} else if (value instanceof List) {
				List list = (List)value;
				for (int i = 0; i < list.size(); i++) {
					createXML((Map)list.get(i), element);
				}
			} else {
				element.addText("<![CDATA[" + value + "]]>");
			}
		}
	}

	public String getXML(HttpServletRequest request) {
		try {
			String recMsg = streamToString(request.getInputStream(), "utf-8"); // 获取微信返回的动作
			// 解析xml内容
			Map<String, String> xmlMap = parseXML(recMsg);
			// 通知微信需要的操作
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("ToUserName", xmlMap.get("FromUserName"));
			map.put("FromUserName", xmlMap.get("ToUserName"));
			String key = xmlMap.get("EventKey");
			org.dom4j.Document document = org.dom4j.DocumentHelper.createDocument();// 创建根节点
			org.dom4j.Element root = document.addElement("xml");
			switch (key) {
				case "V1001_TODAY_MUSIC":
				// 获取微信操作信息
				map.put("CreateTime", new Date().getTime());
				map.put("MsgType", "text");
				map.put("Content", "asdasd");
				// 通知微信需要做的动作
				createXML(map, root);
				return root.asXML().replaceAll("&lt;", "<").replaceAll("&gt;", ">");
			}
		} catch (Exception e) {

		}
		return "";
	}
%>
